import React, { useState, useEffect } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import '@wangeditor/editor/dist/css/style.css';

function MyEditor(props) {
  const { value, onChange = () => {}  } = props
  const [editor, setEditor] = useState(null); // 存储 editor 实例
  const [html, setHtml] = useState('');

  useEffect(() => {
    setHtml(value)
  }, [value]);

  const toolbarConfig = {
    excludeKeys: [
      'fullScreen',
    ],
  };
  const editorConfig = {
    placeholder: '请输入内容...',
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {

    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  const handleChange = (editor) => {
    setHtml(editor.getHtml())
    onChange(editor.getHtml())
  }

  return (
    <>
      <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: '1px solid #ccc' }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={handleChange}
          mode="default"
          style={{ height: '300px' }}
        />
      </div>
      {/* <div style={{ marginTop: '15px' }}>{html}</div> */}
    </>
  );
}

export default MyEditor;
